package com.bytz.modules.cms.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bytz.modules.cms.product.entity.Product;
import com.bytz.modules.cms.product.entity.ProductPackDetail;
import com.bytz.modules.cms.product.mapper.ProductPackDetailMapper;
import com.bytz.modules.cms.product.model.ProductPackDetailModel;
import com.bytz.modules.cms.product.service.IAdminProductPackDetailService;
import com.bytz.modules.cms.product.service.IProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 莱宝CMS—产品管理—产品打包详情关联表 服务实现类
 * </p>
 *
 * @author KyleWang
 * @since 2022-10-10
 */
@Service
public class AdminProductPackDetailServiceImpl extends ServiceImpl<ProductPackDetailMapper, ProductPackDetail> implements IAdminProductPackDetailService {

    @Autowired
    private IProductService productService;

    @Override
    public List<ProductPackDetailModel> getByPackId(String packId) {

        List<ProductPackDetail> details = lambdaQuery()
                .eq(ProductPackDetail::getPackId, packId)
                .list();

        Map<String, Product> productIdMap = productService.getByIds(details.stream().map(ProductPackDetail::getProductId).collect(Collectors.toSet()))
                .stream().collect(Collectors.toMap(Product::getId, p -> p));

        return details.stream().map(detail -> {

            ProductPackDetailModel model = BeanUtil.copyProperties(detail, ProductPackDetailModel.class);
            model.setProduct(productIdMap.get(detail.getProductId()));

            return model;
        }).collect(Collectors.toList());
    }

    @Override
    public void removeByPackId(String id) {

        if (StringUtils.isBlank(id)) {
            return;
        }

        lambdaUpdate()
                .eq(ProductPackDetail::getPackId, id)
                .remove();
    }

}
